package constant.milk.periodapp.util;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.AnimationType;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.impl.AdError;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;

public class MilkAd
{
	private final static int MAX_COUNT = 10;
	private static int COUNT;
	
	// 구글
	private final static String AD_KEY = "DAN-1ib3omqq4o0gy";
	
	// 티스토어
//	private final static String AD_KEY = "DAN-1hvb2v4rtdlya";
	
	// 올레마켓
//	private final static String AD_KEY = "DAN-skv3ujpywi0p";
	
	// 네이버스토어
//	private final static String AD_KEY = "DAN-urpm7nmfnf4z";
	
//	private final static String AD_KEY = "TestClientId";
	
	private Context context = null;
	private LinearLayout linearLayout = null;
	
	/** 아담 광고 뷰 */
	private AdView adamView = null;
	
	public MilkAd(Context context, LinearLayout LinearLayout)
	{
		this.context = context;
		this.linearLayout = LinearLayout;
		this.linearLayout.setVisibility(View.VISIBLE);
		
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		this.linearLayout.setLayoutParams(params);
		
		COUNT = 0;
		
		startAdam();
	}
	
	private void startAdam()
	{
		// Ad@m 광고 뷰 생성 및 설정
		adamView = new AdView(context);
		
		adamOnClickListener();
		
		// 할당 받은 clientId 설정
		adamView.setClientId(AD_KEY);
		
        adamView.setRequestInterval(15);
 		adamView.setAnimationType(AnimationType.FLIP_HORIZONTAL);
 		adamView.setAdCache(true);
 		
 		linearLayout.addView(adamView);
 		
 		adamView.setVisibility(View.VISIBLE);
	}
	
	public void resumeAd()
	{
		if (adamView != null)
		{
			COUNT = 0;
			
			if (linearLayout.getChildCount() > 0)
			{
				linearLayout.removeAllViews();
			}
			
			destoryAd();
			startAdam();
		}
	}
	
	public void destoryAd()
	{
		if (adamView != null)
		{
			adamView.destroy();
			adamView = null;
		}
	}
	
	public void adamOnClickListener()
	{
		if (adamView != null)
		{
			adamView.setOnAdLoadedListener(new OnAdLoadedListener()
			{
				@Override
				public void OnAdLoaded()
				{
					COUNT = 0;
				}
			});
			
			adamView.setOnAdFailedListener(new OnAdFailedListener()
			{
				@Override
				public void OnAdFailed(AdError arg0, String arg1)
				{
					if (COUNT < MAX_COUNT)
					{
						destoryAd();
						startAdam();
						
						COUNT++;
					}
				}
			});
		}
	}
}
